/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.actions;

import controler.formbeans.UpdateCVBean;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.logic.db.AdminFunctionality;
import model.logic.db.CommonWSFunctionality;
import model.logic.db.UserFunctions;
import model.pojo.AboutUs;
import model.pojo.ApplicantCompanies;
import model.pojo.Applicants;
import model.pojo.EducationLevels;
import model.pojo.Institutes;
import model.pojo.StudyFields;
import model.pojo.Users;
import model.pojo.Vacancies;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

/**
 *
 * @author maha
 */
public class UpdateCV extends DispatchAction {

    public ActionForward redirect(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        HttpSession session = request.getSession(false);
        Users user = (Users) session.getAttribute("user");
        CommonWSFunctionality ws = new CommonWSFunctionality();
        Vector<AboutUs> aboutUs = ws.getAboutUsMenuAndContents();
        ((UpdateCVBean) form).setAboutUs(aboutUs);
        UserFunctions uf = new UserFunctions();
        Applicants applicant = uf.getApplicant(user.getUserId());


        if (applicant == null) {
            ((UpdateCVBean) form).setMsg("Sorry, You Didn't apply Before");
            return mapping.findForward("fail");
        }

        AdminFunctionality af = new AdminFunctionality();
        Vector<ApplicantCompanies> appCompanies = af.getAppCompanies(applicant.getApplicantId());


        ((UpdateCVBean) form).setApplicants(applicant);
        ((UpdateCVBean) form).setAcomp(appCompanies);
        ((UpdateCVBean) form).setCountry(uf.getCountries());
        ((UpdateCVBean) form).setElevel(uf.getEduLevels());
        ((UpdateCVBean) form).setInst(uf.getInst());
        ((UpdateCVBean) form).setGrades(uf.getGrades());
        ((UpdateCVBean) form).setStudy(uf.getStudyFields());
        ((UpdateCVBean) form).setVac(uf.getVacncies());
        ((UpdateCVBean) form).setMsg("");
        return mapping.findForward("redir");
    }

    public ActionForward update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward forward = new ActionForward();



        try {
            UpdateCVBean applicant = (UpdateCVBean) form;

//            if (applicant.getCvPath().getFileSize() == 0 || applicant.getCvPath().getFileName().equals("")) {
//
//                ((UpdateCVBean) form).setMsg("You must upload your new C.V.");
//                return mapping.findForward("fail");
//            }

            Applicants applic = new Applicants();

            System.err.println("UserId= ============= " + applicant.getUserId());

            applic.setUserId(applicant.getUserId());
            applic.setGender(applicant.getGender());
            applic.setFirstName(applicant.getFirstName());
            applic.setMiddleName(applicant.getMiddleName());
            applic.setLastName(applicant.getLastName());

            applic.setDateOfBirth(new Date(applicant.getBd()));
            applic.setPlaceOfBirth(applicant.getPlaceOfBirth());
            applic.setMilitaryStatus(applicant.getMilitaryStatus());
            applic.setMaritalyStatus(applicant.getMaritalStatus());
            applic.setDate(new Date());
            applic.setNoOfChildren(applicant.getChildren());
            applic.setNationalId(applicant.getNatid());
            applic.setAddress(applicant.getAdd1());
            applic.setCountry(applicant.getCountries());
            applic.setCity(applicant.getCity());
            applic.setZipcode(applicant.getZipCode());
            applic.setPhone(applicant.getPhone());
            applic.setMobile(applicant.getMob());
            EducationLevels el = new EducationLevels();
            el.setEducationLevelId(applicant.getLevOfEd());
            applic.setEducationLevels(el);
            Institutes inst = new Institutes();
            inst.setInstituteId(applicant.getUniversity());
            applic.setInstitutes(inst);
            applic.setGradeId(applicant.getGrad());
            applic.setGraduationYear(applicant.getGradYear());
            StudyFields sf = new StudyFields();

            System.err.println("study field=+++++++++   " + applicant.getFieldOfStudy());


            sf.setStudyFieldId(applicant.getFieldOfStudy());
            applic.setStudyFields(sf);
            applic.setYearsOfExperince(applicant.getYearsOfExp());

            Vacancies vac = new Vacancies();
            vac.setVacancyId(applicant.getVacancyId());
            applic.setVacancies(vac);



            FormFile file = applicant.getCvPath();


            if (file.getFileName().length() < 1) {
                System.out.println(applicant.getCv());
                applic.setCv(applicant.getCv());
            } else {

                ServletContext servletContext = request.getServletContext();
                String path = "../../web/styles/upload/CVs";


                String filePath = servletContext.getRealPath(path);
                File folder = new File(filePath);
                if (!folder.exists()) {
                    boolean mkdir = folder.mkdir();
                    System.out.println(mkdir);
                }

                String fileName = file.getFileName();

                if (!("").equals(fileName)) {


                    File newFile = new File(filePath, fileName);
                    applic.setCv("styles/upload/CVs/" + newFile.getName());

                    System.out.println(newFile.getCanonicalFile());
                    if (!newFile.exists()) {
                        FileOutputStream fos = new FileOutputStream(newFile);
                        fos.write(file.getFileData());
                        fos.flush();
                        fos.close();
                        System.out.println("Uploaded");
                    }

                }
            }

            UserFunctions uf = new UserFunctions();
            int insertApplicant = uf.mergeApplicant(applic);

            if (insertApplicant != -1) {
//                ApplicantCompanies c1 = new ApplicantCompanies();
//                c1.setApplicantId(insertApplicant);
//                c1.setCompanyName(applicant.getCompName1());
//                c1.setApplicantPosition(applicant.getPos1());
//                c1.setWorkFrom(new Date(applicant.getFrom1()));
//                c1.setWorkTo(new Date(applicant.getTo1()));
//                uf.insertApplicantCompanies(c1);
            }


            ((UpdateCVBean) form).setMsg("Your Information is Updated Successfully");
            forward = mapping.findForward("done");

        } catch (Exception e) {
            e.printStackTrace();
            ((UpdateCVBean) form).setMsg("Failed to update your information");
            forward = mapping.findForward("fail");
        }
        return forward;
    }

    public ActionForward updateCompanies(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        UpdateCVBean bean = (UpdateCVBean) form;
        int applicantId = bean.getApplicantId();

        int companuId = bean.getCompanyId();
        String companyName = bean.getCompanyName();
        String from = bean.getWorkFrom();
        String to = bean.getWorkTo();
        ApplicantCompanies a = new ApplicantCompanies();
        a.setApplicantId(applicantId);
        a.setCompanyId(companuId);
        a.setCompanyName(companyName);
        a.setWorkFrom(new Date(from));
        a.setWorkTo(new Date(to));
        a.setApplicantPosition(bean.getApplicantPosition());

        System.out.println(applicantId + "," + companuId + "," + companyName + "," + from + "," + to + "," + bean.getApplicantPosition());


        UserFunctions uf = new UserFunctions();
        int updateCompany = uf.updateCompany(a);

        if (updateCompany == 1) {
            ((UpdateCVBean) form).setMsg("Your Information is Updated Successfully");
            AdminFunctionality af = new AdminFunctionality();
            Vector<ApplicantCompanies> appCompanies = af.getAppCompanies(applicantId);


            ((UpdateCVBean) form).setAcomp(appCompanies);
            ActionRedirect redirect =
                    new ActionRedirect(mapping.findForward("redir"));
            return redirect;
        } else {
            ((UpdateCVBean) form).setMsg("Your Information Can't Be Updated At a moment");
            ActionRedirect redirect =
                    new ActionRedirect(mapping.findForward("redir"));
            return redirect;

        }

    }

    public ActionForward addCompanies(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        UpdateCVBean bean = (UpdateCVBean) form;
        int applicantId = bean.getApplicantId();

        String companyName = bean.getCompanyName();
        String from = bean.getWorkFrom();
        String to = bean.getWorkTo();
        ApplicantCompanies a = new ApplicantCompanies();
        a.setApplicantId(applicantId);
        a.setCompanyName(companyName);
        a.setWorkFrom(new Date(from));
        a.setWorkTo(new Date(to));
        a.setApplicantPosition(bean.getApplicantPosition());


        UserFunctions uf = new UserFunctions();
        int insertApplicantCompanies = uf.insertApplicantCompanies(a);

        if (insertApplicantCompanies == 1) {
            ((UpdateCVBean) form).setMsg("Company Inserted is inserted Successfully");
            AdminFunctionality af = new AdminFunctionality();
            Vector<ApplicantCompanies> appCompanies = af.getAppCompanies(applicantId);


            ((UpdateCVBean) form).setAcomp(appCompanies);
            ActionRedirect redirect =
                    new ActionRedirect(mapping.findForward("redir"));
            return redirect;
        } else {
            ((UpdateCVBean) form).setMsg("Company Information Can't Be inserted At a moment");
            ActionRedirect redirect =
                    new ActionRedirect(mapping.findForward("redir"));
            return redirect;

        }




    }
}
